package com.qf.springsecurity.service;


import com.qf.springsecurity.mapper.MenuMapper;
import com.qf.springsecurity.mapper.RoleMapper;
import com.qf.springsecurity.mapper.UserMapper;
import com.qf.springsecurity.pojo.Menu;
import com.qf.springsecurity.pojo.Role;
import com.qf.springsecurity.pojo.Users;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;


import java.util.ArrayList;
import java.util.List;

@Service
public class MyUserDetailService implements UserDetailsService {

    private UserMapper userMapper;
    private RoleMapper roleMapper;
    private MenuMapper menuMapper;

    @Autowired
    public void setRoleMapper(RoleMapper roleMapper) {
        this.roleMapper = roleMapper;
    }

    @Autowired
    public void setMenuMapper(MenuMapper menuMapper) {
        this.menuMapper = menuMapper;
    }

    @Autowired
    public void setUserMapper(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    //    因为我们用户传过来的密码是一个明文，但是数据库中存放的是密文，所以只能先根据用户名查出来密码然后再计算一次就行比对
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//      通过登录用户名  查询该名用户
        Users users = userMapper.findUsersByName(username);
        if (users == null) {
            return null;
        }
        System.out.println(users);

//      根据用户ID 查询到所有的角色，一个用户可以拥有多个角色
        List<Role> roleList = roleMapper.findAllRolesByUserId(users.getId());
//      遍历每个角色 获取每个角色的权限，每个角色拥有不同的权限
        roleList.forEach(role -> {
//            查询当前角色的所有菜单，也就是权限 能访问哪些
            List<Menu> menuList = menuMapper.findMenusByRoleId(role.getId());
            role.setMenuList(menuList);
        });


//        spring security 需要的权限集合
        List<SimpleGrantedAuthority> list = new ArrayList<>();
        System.out.println("ID" + roleList);
//        遍历用户的角色 将信息保存到新的权限集合中
        for (Role role : roleList) {
//            将角色设置到对象的权限中

            list.add(new SimpleGrantedAuthority("ROLE_" + role.getName()));
            List<Menu> roleMenuList = role.getMenuList();
            System.out.println("wwwwww" + roleMenuList);
            for (Menu menu : roleMenuList) {
//                以菜单的别名（权限） 作为参数创建对象保存到集合中
                list.add(new SimpleGrantedAuthority(menu.getPerms()));
            }
        }
        User user = new User(username, users.getPassword(), list);

        return user;
    }
}
